import strJobSeekerPageHtml from "./JobSeekerPage.html";
import { DomUtils } from "../../utils/DomUtils";
import { jobSeekerService } from "../../services/jobSeekerService.js";
import { interviewInvitationService } from "../../services/interviewInvitationService";
import { companyJobService } from "../../services/companyJobService";

export class JobSeekerPage {
  constructor() {
    this.currentPage = 1;
    this.pageSize = 10;
    this.searchKeyword = "";
    this.searchType = "id";
    this.totalPages = 0;
    this.totalItems = 0;
    this.selectedJobSeekers = new Set();
  }

  render() {
    const dom = DomUtils.convertToDom(strJobSeekerPageHtml);
    this._bindElements(dom);
    this._bindEvents(dom);
    this._loadData();
    return dom;
  }

  _bindElements(dom) {
    this.searchTypeSelect = dom.querySelector("#searchType");
    this.searchInput = dom.querySelector("#searchInput");
    this.searchBtn = dom.querySelector("#searchBtn");
    this.addJobSeekerBtn = dom.querySelector("#addJobSeekerBtn");
    this.batchDeleteBtn = dom.querySelector("#batchDeleteBtn");
    this.selectAllCheckbox = dom.querySelector("#selectAll");
    this.jobSeekerTableBody = dom.querySelector("#jobSeekerTableBody");
    this.pagination = dom.querySelector("#pagination");
    this.jobSeekerModal = dom.querySelector("#jobSeekerModal");
    this.jobSeekerForm = dom.querySelector("#jobSeekerForm");
    this.modalClose = dom.querySelector("#modalClose");
    this.jobSeekerId = dom.querySelector("#jobSeekerId");
    this.nameInput = dom.querySelector("#name");
    this.genderSelect = dom.querySelector("#gender");
    this.emailInput = dom.querySelector("#email");
    this.phoneInput = dom.querySelector("#phone");
    this.expectedSalaryInput = dom.querySelector("#expectedSalary");
    this.positionInput = dom.querySelector("#position");
    this.workLocationInput = dom.querySelector("#workLocation");
    this.certificatesTextarea = dom.querySelector("#certificates");
    this.workExperienceTextarea = dom.querySelector("#workExperience");
    this.personalIntroTextarea = dom.querySelector("#personalIntro");
    this.inviteModal = dom.querySelector("#inviteModal");
  }

  _bindEvents(dom) {
    this.searchBtn?.addEventListener("click", async () => {
      const searchValue = this.searchInput.value.trim();
      const searchType = this.searchTypeSelect.value;

      if (!searchValue) {
        this._showError("请输入搜索内容");
        return;
      }

      try {
        let jobSeekers;
        if (searchType === "id") {
          const id = parseInt(searchValue);
          if (isNaN(id)) {
            this._showError("请输入有效的求职者ID");
            return;
          }
          const jobSeeker = await jobSeekerService.getJobSeeker(id);
          jobSeekers = jobSeeker ? [jobSeeker] : [];
        } else {
          // 获取所有求职者并在前端进行模糊匹配
          const allJobSeekers = await jobSeekerService.getJobSeekers(1, 1000);
          jobSeekers = allJobSeekers.items.filter((js) => {
            if (searchType === "name") {
              return (
                js.name &&
                js.name.toLowerCase().includes(searchValue.toLowerCase())
              );
            } else if (searchType === "email") {
              return (
                js.email &&
                js.email.toLowerCase().includes(searchValue.toLowerCase())
              );
            }
            return false;
          });
        }

        if (jobSeekers.length > 0) {
          this._renderTable(jobSeekers);
          this._hidePagination();
          this._addBackButton();
        } else {
          this._showError(
            `未找到${
              searchType === "id"
                ? "求职者ID"
                : searchType === "name"
                ? "姓名"
                : "邮箱"
            }包含 "${searchValue}" 的求职者`
          );
        }
      } catch (error) {
        console.error("Error searching job seekers:", error);
        this._showError("查询失败：" + error.message);
      }
    });

    this.searchInput?.addEventListener("keypress", (e) => {
      if (e.key === "Enter") this.searchBtn.click();
    });

    this.pagination?.addEventListener("click", (e) => {
      e.preventDefault();
      if (e.target.tagName === "A") {
        this.currentPage = parseInt(e.target.dataset.page);
        this._loadData();
      }
    });

    this.addJobSeekerBtn?.addEventListener("click", () => this._showAddModal());
    this.batchDeleteBtn?.addEventListener("click", () =>
      this._handleBatchDelete()
    );
    this.selectAllCheckbox?.addEventListener("change", (e) =>
      this._handleSelectAll(e)
    );
    this.jobSeekerForm?.addEventListener("submit", (e) =>
      this._handleFormSubmit(e)
    );
    this.modalClose?.addEventListener("click", () => this._hideModal());

    if (this.inviteModal) {
      const cancelBtn = this.inviteModal.querySelector(
        'button[data-dismiss="modal"]'
      );
      if (cancelBtn) {
        cancelBtn.addEventListener("click", () => {
          $(this.inviteModal).modal("hide");
        });
      }

      const submitBtn = this.inviteModal.querySelector("#submitInvite");
      if (submitBtn) {
        submitBtn.addEventListener("click", (e) =>
          this._handleInviteFormSubmit(e)
        );
      }
    }

    this.jobSeekerTableBody?.addEventListener("click", async (e) => {
      const btn = e.target.closest("button");
      if (!btn) return;

      const id = btn.dataset.id;
      if (btn.classList.contains("delete-btn")) {
        if (confirm("确认删除该求职者？")) {
          await jobSeekerService.deleteJobSeeker(id);
          this._loadData();
        }
      } else if (btn.classList.contains("edit-btn")) {
        await this._showEditModal(id);
      } else if (btn.classList.contains("detail-btn")) {
        await this._showDetailModal(id);
      } else if (btn.classList.contains("invite-btn")) {
        const row = btn.closest("tr");
        const name = row.querySelector("td:nth-child(3)").textContent;
        const email = row.querySelector("td:nth-child(5)").textContent;
        await this._showInviteModal(id, name, email);
      }
    });
  }

  async _loadData() {
    try {
      const response = await jobSeekerService.getJobSeekers(
        this.currentPage,
        this.pageSize,
        this.searchType,
        this.searchKeyword
      );

      // 确保数据格式正确
      const items = Array.isArray(response.items) ? response.items : [];
      this.totalItems = response.total || items.length;
      this.totalPages =
        response.totalPages || Math.ceil(this.totalItems / this.pageSize);

      this._renderTable(items);
      this._renderPagination();
    } catch (error) {
      console.error("Error loading job seekers:", error);
      this._showError("加载求职者数据失败");
    }
  }

  _renderTable(jobSeekers) {
    if (!Array.isArray(jobSeekers)) {
      console.error("Invalid job seekers data:", jobSeekers);
      this._showError("数据格式错误");
      return;
    }

    this.jobSeekerTableBody.innerHTML = "";
    jobSeekers.forEach((jobSeeker) => {
      const row = document.createElement("tr");
      row.innerHTML = `
        <td>
          <div class="custom-checkbox custom-control">
            <input
              type="checkbox"
              class="custom-control-input"
              id="select-${jobSeeker.id}"
              data-id="${jobSeeker.id}"
            />
            <label
              for="select-${jobSeeker.id}"
              class="custom-control-label"
            ></label>
          </div>
        </td>
        <td>${jobSeeker.id || "-"}</td>
        <td>${jobSeeker.name || "-"}</td>
        <td>${jobSeeker.gender || "-"}</td>
        <td>${jobSeeker.email || "-"}</td>
        <td>${jobSeeker.phone || "-"}</td>
        <td>${jobSeeker.expectedSalary || "-"}</td>
        <td>${jobSeeker.position || "-"}</td>
        <td>${jobSeeker.workLocation || "-"}</td>
        <td>
          <button class="btn btn-info btn-sm detail-btn" data-id="${
            jobSeeker.id
          }">
            <i class="fas fa-eye"></i> 详情
          </button>
          <button class="btn btn-primary btn-sm edit-btn" data-id="${
            jobSeeker.id
          }">
            <i class="fas fa-edit"></i> 编辑
          </button>
          <button class="btn btn-success btn-sm invite-btn" data-id="${
            jobSeeker.id
          }">
            <i class="fas fa-envelope"></i> 面试邀请
          </button>
          <button class="btn btn-danger btn-sm delete-btn" data-id="${
            jobSeeker.id
          }">
            <i class="fas fa-trash"></i> 删除
          </button>
        </td>
      `;
      this.jobSeekerTableBody.appendChild(row);

      // Add event listeners for buttons
      const detailBtn = row.querySelector(".detail-btn");
      const editBtn = row.querySelector(".edit-btn");
      const deleteBtn = row.querySelector(".delete-btn");
      const inviteBtn = row.querySelector(".invite-btn");
      const checkbox = row.querySelector(`#select-${jobSeeker.id}`);

      detailBtn.addEventListener("click", () =>
        this._showDetailModal(jobSeeker.id)
      );
      editBtn.addEventListener("click", () =>
        this._showEditModal(jobSeeker.id)
      );
      deleteBtn.addEventListener("click", () =>
        this._handleDelete(jobSeeker.id)
      );
      inviteBtn.addEventListener("click", () =>
        this._showInviteModal(jobSeeker.id, jobSeeker.name, jobSeeker.email)
      );
      checkbox.addEventListener("change", (e) =>
        this._handleSelect(e, jobSeeker.id)
      );
    });

    if (jobSeekers.length === 0) {
      this._showNoData();
    }
  }

  _renderPagination() {
    // 计算要显示的页码范围
    let startPage = Math.max(1, this.currentPage - 2);
    let endPage = Math.min(this.totalPages, startPage + 4);

    // 调整startPage确保始终显示5个页码（如果有）
    if (endPage - startPage < 4) {
      startPage = Math.max(1, endPage - 4);
    }

    let pages = [];

    // 添加首页按钮
    pages.push(`
      <li class="page-item ${this.currentPage === 1 ? "disabled" : ""}">
        <a class="page-link" href="#" data-page="1" title="首页">
          <i class="fas fa-angle-double-left"></i>
        </a>
      </li>
    `);

    // 添加上一页按钮
    pages.push(`
      <li class="page-item ${this.currentPage === 1 ? "disabled" : ""}">
        <a class="page-link" href="#" data-page="${
          this.currentPage - 1
        }" title="上一页">
          <i class="fas fa-angle-left"></i>
        </a>
      </li>
    `);

    // 生成页码按钮
    for (let i = startPage; i <= endPage; i++) {
      pages.push(`
        <li class="page-item ${i === this.currentPage ? "active" : ""}">
          <a class="page-link" href="#" data-page="${i}">${i}</a>
        </li>
      `);
    }

    // 添加下一页按钮
    pages.push(`
      <li class="page-item ${
        this.currentPage === this.totalPages ? "disabled" : ""
      }">
        <a class="page-link" href="#" data-page="${
          this.currentPage + 1
        }" title="下一页">
          <i class="fas fa-angle-right"></i>
        </a>
      </li>
    `);

    // 添加末页按钮
    pages.push(`
      <li class="page-item ${
        this.currentPage === this.totalPages ? "disabled" : ""
      }">
        <a class="page-link" href="#" data-page="${
          this.totalPages
        }" title="末页">
          <i class="fas fa-angle-double-right"></i>
        </a>
      </li>
    `);

    // 渲染分页
    this.pagination.innerHTML = pages.join("");
  }

  _hidePagination() {
    this.pagination.style.display = "none";
  }

  _showAddModal() {
    this.jobSeekerId.value = "";
    this.jobSeekerForm.reset();
    this.jobSeekerModal.classList.add("show");
    this.jobSeekerModal.style.display = "block";
  }

  async _showEditModal(id) {
    try {
      const jobSeeker = await jobSeekerService.getJobSeeker(id);
      this.jobSeekerId.value = jobSeeker.id;
      this.nameInput.value = jobSeeker.name;
      this.genderSelect.value = jobSeeker.gender;
      this.emailInput.value = jobSeeker.email;
      this.phoneInput.value = jobSeeker.phone;
      this.expectedSalaryInput.value = jobSeeker.expectedSalary;
      this.positionInput.value = jobSeeker.position;
      this.workLocationInput.value = jobSeeker.workLocation;
      this.certificatesTextarea.value = jobSeeker.certificates;
      this.workExperienceTextarea.value = jobSeeker.workExperience;
      this.personalIntroTextarea.value = jobSeeker.personalIntro;
      this.jobSeekerModal.classList.add("show");
      this.jobSeekerModal.style.display = "block";
    } catch (error) {
      console.error("Error loading job seeker:", error);
      alert("加载求职者信息失败");
    }
  }

  _hideModal() {
    this.jobSeekerModal.classList.remove("show");
    this.jobSeekerModal.style.display = "none";
  }

  async _handleFormSubmit(e) {
    e.preventDefault();
    const formData = {
      name: this.nameInput.value,
      gender: this.genderSelect.value,
      email: this.emailInput.value,
      phone: this.phoneInput.value,
      expectedSalary: this.expectedSalaryInput.value,
      position: this.positionInput.value,
      workLocation: this.workLocationInput.value,
      certificates: this.certificatesTextarea.value,
      workExperience: this.workExperienceTextarea.value,
      personalIntro: this.personalIntroTextarea.value,
    };

    try {
      if (this.jobSeekerId.value) {
        await jobSeekerService.updateJobSeeker(
          this.jobSeekerId.value,
          formData
        );
        alert("更新成功");
      } else {
        await jobSeekerService.createJobSeeker(formData);
        alert("创建成功");
      }
      this._hideModal();
      this._loadData();
    } catch (error) {
      console.error("Error saving job seeker:", error);
      alert("保存失败");
    }
  }

  async _handleDelete(id) {
    if (!confirm("确定要删除这个求职者吗？")) return;

    try {
      await jobSeekerService.deleteJobSeeker(id);
      alert("删除成功");
      this._loadData();
    } catch (error) {
      console.error("Error deleting job seeker:", error);
      alert("删除失败");
    }
  }

  _handleSelectAll(e) {
    const checkboxes = this.jobSeekerTableBody.querySelectorAll(
      "input[type='checkbox']"
    );
    checkboxes.forEach((checkbox) => {
      checkbox.checked = e.target.checked;
      const id = checkbox.dataset.id;
      if (e.target.checked) {
        this.selectedJobSeekers.add(id);
      } else {
        this.selectedJobSeekers.delete(id);
      }
    });
    this.batchDeleteBtn.disabled = this.selectedJobSeekers.size === 0;
  }

  _handleSelect(e, id) {
    if (e.target.checked) {
      this.selectedJobSeekers.add(id);
    } else {
      this.selectedJobSeekers.delete(id);
    }
    this.batchDeleteBtn.disabled = this.selectedJobSeekers.size === 0;
  }

  async _handleBatchDelete() {
    if (this.selectedJobSeekers.size === 0) return;
    if (
      !confirm(`确定要删除选中的 ${this.selectedJobSeekers.size} 个求职者吗？`)
    )
      return;

    try {
      await jobSeekerService.batchDeleteJobSeekers(
        Array.from(this.selectedJobSeekers)
      );
      alert("批量删除成功");
      this.selectedJobSeekers.clear();
      this.selectAllCheckbox.checked = false;
      this.batchDeleteBtn.disabled = true;
      this._loadData();
    } catch (error) {
      console.error("Error batch deleting job seekers:", error);
      alert("批量删除失败");
    }
  }

  _showError(message) {
    this.jobSeekerTableBody.innerHTML = `
      <tr>
        <td colspan="10" class="text-center text-danger">
          ${message}
        </td>
      </tr>
    `;
  }

  _showNoData() {
    this.jobSeekerTableBody.innerHTML = `
      <tr>
        <td colspan="10" class="text-center">
          暂无数据
        </td>
      </tr>
    `;
  }

  async _showDetailModal(id) {
    try {
      const jobSeeker = await jobSeekerService.getJobSeeker(id);
      const modal = document.createElement("div");
      modal.className = "modal fade";
      modal.id = "detailModal";
      modal.innerHTML = `
        <div class="modal-dialog modal-lg">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">求职者详情</h5>
              <button type="button" class="close" data-dismiss="modal">
                <span>&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <div class="row">
                <div class="col-md-6">
                  <p><strong>ID:</strong> ${jobSeeker.id || "-"}</p>
                  <p><strong>姓名:</strong> ${jobSeeker.name || "-"}</p>
                  <p><strong>性别:</strong> ${jobSeeker.gender || "-"}</p>
                  <p><strong>邮箱:</strong> ${jobSeeker.email || "-"}</p>
                  <p><strong>电话:</strong> ${jobSeeker.phone || "-"}</p>
                </div>
                <div class="col-md-6">
                  <p><strong>期望薪资:</strong> ${
                    jobSeeker.expectedSalary || "-"
                  }</p>
                  <p><strong>期望职位:</strong> ${jobSeeker.position || "-"}</p>
                  <p><strong>期望工作地点:</strong> ${
                    jobSeeker.workLocation || "-"
                  }</p>
                  <p><strong>证书:</strong> ${jobSeeker.certificates || "-"}</p>
                </div>
              </div>
              <div class="row mt-3">
                <div class="col-12">
                  <p><strong>工作经验:</strong></p>
                  <div class="border p-2">${
                    jobSeeker.workExperience || "-"
                  }</div>
                </div>
              </div>
              <div class="row mt-3">
                <div class="col-12">
                  <p><strong>个人介绍:</strong></p>
                  <div class="border p-2">${
                    jobSeeker.personalIntro || "-"
                  }</div>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
            </div>
          </div>
        </div>
      `;

      document.body.appendChild(modal);
      const modalInstance = new bootstrap.Modal(modal);
      modalInstance.show();

      modal.addEventListener("hidden.bs.modal", () => {
        modal.remove();
      });
    } catch (error) {
      console.error("Error loading job seeker details:", error);
      alert("加载求职者详情失败");
    }
  }

  async _showInviteModal(seekerId, seekerName, seekerEmail) {
    if (!this.inviteModal) {
      console.error("Invite modal not found");
      return;
    }

    // Set seeker information
    this.inviteModal.querySelector("#seekerId").value = seekerId;
    this.inviteModal.querySelector("#seekerName").value = seekerName;
    this.inviteModal.querySelector("#seekerEmail").value = seekerEmail;

    // Load company jobs
    try {
      const response = await companyJobService.getCompanyJobs();
      console.log("Loaded company jobs response:", response);

      const jobSelect = this.inviteModal.querySelector("#companyJobId");
      jobSelect.innerHTML = '<option value="">请选择职位</option>';

      // Check if response has items property (pagination format)
      const jobs = response.items || response;

      if (Array.isArray(jobs)) {
        jobs.forEach((job) => {
          console.log("Processing job:", job); // 添加详细的职位数据日志
          const option = document.createElement("option");
          option.value = job.id;
          // 使用正确的字段名称
          const jobTitle = job.jobTitle || "未命名职位";
          const companyName = job.companyName || "未知公司";
          option.textContent = `${jobTitle} - ${companyName}`;
          option.dataset.companyName = job.companyName || "";
          option.dataset.companyEmail = job.companyEmail || "";
          option.dataset.contactPhone = job.contactPhone || "";
          jobSelect.appendChild(option);
        });
      } else {
        console.error("Invalid jobs data format:", jobs);
        throw new Error("职位数据格式不正确");
      }

      // Add change event listener to job select
      jobSelect.addEventListener("change", (e) => {
        const selectedOption = e.target.options[e.target.selectedIndex];
        if (selectedOption.value) {
          this.inviteModal.querySelector("#companyName").value =
            selectedOption.dataset.companyName;
          this.inviteModal.querySelector("#companyEmail").value =
            selectedOption.dataset.companyEmail;
          this.inviteModal.querySelector("#contactPhone").value =
            selectedOption.dataset.contactPhone;
        }
      });

      // Show modal using jQuery
      $(this.inviteModal).modal("show");
    } catch (error) {
      console.error("Error loading company jobs:", error);
      alert("加载职位信息失败：" + error.message);
    }
  }

  async _handleInviteFormSubmit(e) {
    e.preventDefault();

    try {
      // 获取所有必要的字段
      const seekerId = document.getElementById("seekerId").value;
      const seekerName = document.getElementById("seekerName").value;
      const seekerEmail = document.getElementById("seekerEmail").value;
      const companyName = document.getElementById("companyName").value;
      const companyEmail = document.getElementById("companyEmail").value;
      const contactPhone = document.getElementById("contactPhone").value;
      const companyJobId = document.getElementById("companyJobId").value;
      const invitationTitle = document.getElementById("invitationTitle").value;
      const interviewTime = document.getElementById("interviewTime").value;
      const interviewLocation =
        document.getElementById("interviewLocation").value;
      const interviewNotes = document.getElementById("interviewNotes").value;

      // 验证必填字段
      if (
        !seekerId ||
        !companyJobId ||
        !invitationTitle ||
        !interviewTime ||
        !interviewLocation
      ) {
        alert("请填写所有必填字段");
        return;
      }

      // 验证日期格式
      const interviewDate = new Date(interviewTime);
      if (isNaN(interviewDate.getTime())) {
        alert("请输入有效的面试时间");
        return;
      }

      // 构建邀请数据
      const invitationData = {
        jobSeekerId: parseInt(seekerId, 10),
        companyJobId: parseInt(companyJobId, 10),
        invitationTitle: invitationTitle.trim(),
        invitationTime: interviewDate.toISOString(),
        interviewLocation: interviewLocation.trim(),
        invitationDetails: interviewNotes ? interviewNotes.trim() : "无",
        status: "PENDING",
        seekerName: seekerName.trim(),
        seekerEmail: seekerEmail.trim(),
        companyName: companyName.trim(),
        companyEmail: companyEmail.trim(),
        contactPhone: contactPhone ? contactPhone.trim() : "",
      };

      console.log("Sending invitation data:", invitationData);

      // 发送邀请
      const response =
        await interviewInvitationService.createInterviewInvitation(
          invitationData
        );

      if (response) {
        alert("面试邀请发送成功！");
        // 关闭模态框
        $(this.inviteModal).modal("hide");
        // 刷新页面以显示最新数据
        this._loadData();
      } else {
        throw new Error("发送邀请失败：服务器返回空响应");
      }
    } catch (error) {
      console.error("发送面试邀请失败:", error);
      alert(error.message || "发送面试邀请失败，请重试");
    }
  }

  _addBackButton() {
    // 添加返回按钮
    const backButton = document.createElement("button");
    backButton.className = "btn btn-secondary btn-sm ml-2";
    backButton.innerHTML = '<i class="fas fa-arrow-left"></i> 返回列表';
    backButton.onclick = () => {
      this._loadData();
      backButton.remove();
    };

    this.searchBtn.parentNode.insertBefore(
      backButton,
      this.searchBtn.nextSibling
    );
  }
}
